/*
Autor: Alexander Savochkin, 2010
New BSD License
*/

#include "Channel.h"

namespace SRCLF {

	Channel::~Channel()
	{
		delete regulator;
		delete operated_input;
		delete operated_output;
	}


	bool Channel::keep(optional<double> value)
	{
		if(regulator == NULL) 
			return false;

		double known_value;
		if(value)
			known_value = value.get();
		else
			known_value = operated_input->getInput();

		if (!regulator_enabled)
		{
			double current_input = operated_input->getInput();
			double current_output = operated_output->getOutput();
			ptime current_time = microsec_clock::universal_time();
			regulator->init(current_input, current_output, current_time);
			regulator_enabled = true;
		}

		regulator->setDesired( known_value );
		return true;
	}

	void Channel::update(const ptime& current_time)
	{
		operated_input->update(current_time);
		operated_output->update(current_time);
		double current_input_value = operated_input->getInput();
		regulator->update(current_input_value, current_time);
		if (regulator_enabled) 
			operated_output->setOutput( regulator->getRegulatorValue() );

		next_control_moment += control_interval;
	}

} //namespace SRCLF
